walletSweeper.then   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
nc 1
dl 0
loc 3
rs 10
nop 1
1
var blocktrail = require('../');
2
3
/**
4
 * backup data from a Wallet V1 Backup PDF (Developer wallets)
5
 *
6
 * walletVersion:       the version number of the created wallet
7
 * primaryMnemonic:     the primary mnemonic, obtained from our backup pdf
8
 * primaryPassphrase:   our wallet passphrase, as used to unlock the wallet when sending transactions
9
 * backupMnemonic:      the backup mnemonic, obtained from our backup pdf
10
 * blocktrailKeys:      an array of the blocktrail pubkeys objects as {keyIndex: keyIndex, path: path, pubkey: pubkey}
11
 *                          keyIndex:   key index printed below each pubkey QR code on the backup pdf
12
 *                          path:       path printed below each pubkey QR code on the backup pdf
13
 *                          pubkey:     the contents of the QR code
14
 */
15
var backupDataV1 = {
16
    walletVersion:      1,
17
    primaryMnemonic:    "plug employ detail flee ethics junior cover surround aspect slender venue faith devote ice sword camp pepper baby decrease mushroom feel endless cactus group deposit achieve cheese fire alone size enlist sail labor pulp venture wet gas object fruit dutch industry lend glad category between hidden april network",
18
    primaryPassphrase:  "test",
19
    backupMnemonic:     "disorder husband build smart also alley uncle buffalo scene club reduce fringe assault inquiry damage gravity receive champion coffee awesome conduct two mouse wisdom super lend dice toe emotion video analyst worry charge sleep bless pride motion oxygen congress jewel push bag ozone approve enroll valley picnic flight",
20
    blocktrailKeys: [
21
        {
22
            keyIndex: 0,
23
            path:     "M/0'",
24
            pubkey:   'tpubD8UrAbbGkiJUnZY91vYMX2rj7zJRGH7snQ1g9H1waU39U74vE8HAfMCZdBByRJhVHq2B9X6uZcA2VaCJwnPN3zXLAPjETsfPGwAgWgEFvVk'
25
        },
26
        {
27
            keyIndex: 9999,
28
            path:     "M/9999'",
29
            pubkey:   'tpubD9q6vq9zdP3gbhpjs7n2TRvT7h4PeBhxg1Kv9jEc1XAss7429VenxvQTsJaZhzTk54gnsHRpgeeNMbm1QTag4Wf1QpQ3gy221GDuUCxgfeZ'
30
        }
31
    ]
32
};
33
34
35
/**
36
 * backup data from a Wallet V2 Backup PDF (Consumer web and mobile wallets)
37
 *
38
 * walletVersion:               the version number of the created wallet
39
 * encryptedPrimaryMnemonic:    the "Encrypted Primary Seed" mnemonic, obtained from our backup pdf (page 1)
40
 * backupMnemonic:              the "backup seed" mnemonic, obtained from our backup pdf (page 1)
41
 *
42
 * passwordEncryptedSecretMnemonic: the "password encrypted secret" mnemonic, obtained from our backup pdf (page 2)
43
 * password:                        our wallet password, as used to unlock the wallet when sending transactions
44
 *
45
 * encryptedRecoverySecretMnemonic: the "Encrypted Recovery Secret" an alternative to the password and encrypted secret, if the password is forgotten (page 1)
46
 * recoverySecretDecryptionKey:     required to decrypt the encrypted recovery secret. Must be obtained from Blocktrail via [email protected]
47
 *
48
 * blocktrailKeys:                  an array of the blocktrail pubkeys objects as {keyIndex: keyIndex, path: path, pubkey: pubkey}
49
 *                                      keyIndex:   key index printed below each pubkey QR code on the backup pdf (page 1)
50
 *                                      path:       path printed below each pubkey QR code on the backup pdf (page 1)
51
 *                                      pubkey:     the contents of the QR code (page 1)
52
 */
53
var backupDataV2 = {
54
    walletVersion:                   2,
55
    encryptedPrimaryMnemonic:        "fat arena brown skull echo quiz diesel beach gift olympic riot orphan sketch chief exchange height danger nasty clutch dune wing run drastic roast exist super toddler combine vault salute salad trap spider tenant draw million insane alley pelican spot alpha cheese version clog arm tomorrow slush plunge",
56
    backupMnemonic:                  "aerobic breeze taste swear whip service bone siege tackle grow drip few tray clay crumble glass athlete bronze office roast learn tuition exist symptom",
57
58
    passwordEncryptedSecretMnemonic: "fat arena brown skull echo quick damage toe later above jewel life void despair outer model annual various original stool answer vessel tired fragile visa summer step dash inform unit member social liberty valve tonight ocean pretty dial ability special angry like ancient unit shiver safe hospital ocean around poet album split they random decide ginger guilt mix evolve click avoid oven sad gospel worry chaos another lonely essence lucky health view",
59
    password:                        "test",
60
61
    blocktrailKeys: [
62
        {
63
            keyIndex: 0,
64
            path:     "M/0'",
65
            pubkey:   'xpub687DeMmb3SM2WUySJREg6F2vvRCQE1uSHcm5DY6HKyJe5oCczqavKHWUS8e5hDdx5bU4EWzFq9vSRSbi2rEYShdw6ectgbxAqmBgg8ZaqtC'
66
        }
67
    ]
68
};
69
70
// use testnet or not? (NB: backupDataV1 is testnet, while backupDataV2 is mainnet)
71
var useTestnet = false;
72
73
74
// we need a bitcoin data service to find utxos. We'll use the BlocktraiBitcoinService, which in turn uses the Blocktrail SDK
75
var bitcoinDataClient = new blocktrail.BlocktrailBitcoinService({
76
    apiKey:     "MY_APIKEY",
77
    apiSecret:  "MY_APISECRET",
78
    network:    "BTC",
79
    testnet:    useTestnet
80
});
81
// there is also an Insight data service using bitpay's API
82
// bitcoinDataClient = new blocktrail.InsightBitcoinService({testnet: useTestnet});
83
84
85
86
87
var discoverAndSweep = false;        //do we want to discover funds and sweep them to another wallet at the same time?
88
var recoverWithPassword = false;     //do we want to try and recover with or without the password?
89
90
91
/**
92
 * create an instance of the wallet sweeper, which generates the wallet keys from the backup data
93
 *
94
 */
95
var sweeperOptions = {
96
    network: 'btc',
97
    testnet: useTestnet,
98
    logging: true,          // display extra info in console
99
    sweepBatchSize: 100     // number of addresses to check at a time (use a larger number for older wallets)
100
};
101
var walletSweeper;
102
if (recoverWithPassword) {
103
    console.log('Creating wallet keys using password method...');
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
104
    //walletSweeper = new blocktrail.WalletSweeper(backupDataV1, bitcoinDataClient, sweeperOptions);  //version 1, testnet
105
    walletSweeper = new blocktrail.WalletSweeper(backupDataV2, bitcoinDataClient, sweeperOptions);      //version 2, mainnet
106
} else {
107
    /**
108
     * if the wallet password is forgotten for a V2 wallet, it is possible to use the "Encrypted Recovery Secret" on the backup pdf
109
     * along with a decryption key which must be obtained directly from Blocktrail.
110
     */
111
    backupDataV2.password = null;
112
    backupDataV2.encryptedRecoverySecretMnemonic = "fat arena brown skull echo question sphere farm witness slender hospital note sketch two level ten oyster interest oppose stable method left fringe damage shiver tumble help group eyebrow recipe also another front account apart tomato trigger daring slush magic lunch clump knife cloth measure tool tower hood define salute reopen cover sad bag scan kingdom fault tag increase snap cruise input amused once spring skin grief syrup actual legend tribe emotion";
113
    backupDataV2.recoverySecretDecryptionKey = "86e23bddc80dfb93fc4b05cbfae9c08b6d7398014c52232541237dfe2faaf963";
114
115
    console.log('Creating wallet keys using encrypted secret method...');
116
    //walletSweeper = new blocktrail.WalletSweeper(backupDataV1, bitcoinDataClient, sweeperOptions);  //version 1, testnet
117
    walletSweeper = new blocktrail.WalletSweeper(backupDataV2, bitcoinDataClient, sweeperOptions);      //version 2, mainnet
118
}
119
120
121
/**
122
 * now we can discover funds in the wallet, and then create a transaction to send them all to a new address
123
 *
124
 */
125
if (!discoverAndSweep) {
126
    //Do wallet fund discovery - can be run separately from sweeping
127
    console.log('-----Discovering Funds-----');
128
    var batchSize = 25;
129
    walletSweeper.discoverWalletFunds(batchSize)
130
        .progress(function(progress) {
131
            console.info(progress);
132
        })
133
        .then(function(result) {
134
            console.log(result);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
135
        })
136
        .catch(function(err) {
137
            console.error(err);
138
        });
139
140
} else {
141
    // Do wallet fund discovery and sweeping - if successful you will be returned a signed transaction ready to submit to the network
142
    console.log('\n-----Sweeping Wallet-----');
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
143
    //var receivingAddress = "2NCfSZa6f8YwAnjvGcorGDdMSyY9kMzQTZe";     //testnet address in wallet 1
144
    var receivingAddress = "3EBzEG5g23gTFCW6LE8uf7tVx8WpKpVUUd";        //mainnet address in wallet 2
145
    walletSweeper.sweepWallet(receivingAddress)
146
        .progress(function(progress) {
147
            console.info(progress);
148
        })
149
        .then(function(result) {
150
            console.log(result);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
151
        })
152
        .catch(function(err) {
153
            console.error(err);
154
        });
155
156
}
157